package com.tanhua.appserver.interceptor;

import com.tanhua.model.domain.User;
import com.tanhua.appserver.hanlder.UserHolder;
import com.tanhua.commons.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取传输过来的token
        String token = request.getHeader("Authorization");
        boolean verifyToken = JwtUtil.verifyToken(token);
        if (!verifyToken){
            //拦截
            response.setStatus(401);
            return false;
        }
        //取出存在token中的id和phone
        Claims claims = JwtUtil.getClaims(token);
        Integer id = (Integer) claims.get("id");
        String phone = (String) claims.get("mobbie");
        //将数据封装到user中
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(phone);
        //调用工具类存入LocalThread线程中
        UserHolder.set(user);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //解决完，移除LocalThread中的数据，防止内存溢出
        UserHolder.remove();

    }
}
